//
//  DragCardViewController.m
//  SG
//
//  Created by FISH on 2018/4/25.
//  Copyright © 2018年 yimindai. All rights reserved.
//
#define loginButtonHeight 40
#import "DragCardViewController.h"

@interface DragCardViewController ()<YSLDraggableCardContainerDelegate, YSLDraggableCardContainerDataSource,UIScrollViewDelegate>

@property (nonatomic, strong) YSLDraggableCardContainer *container;

@property (weak, nonatomic) IBOutlet UIView *navigationView;

@property (weak, nonatomic) IBOutlet UIButton *leftButton;

@property (weak, nonatomic) IBOutlet UILabel *contentLabel;

@property (weak, nonatomic) IBOutlet UIView *SegmentView;

@property (weak, nonatomic) IBOutlet UIButton *loginButton;

@property (strong, nonatomic) UIView *showView;

@property (strong, nonatomic) UILabel *showLabel;

@property (strong, nonatomic) UIScrollView *showScrollView;

@property (assign, nonatomic) BOOL check;

@property (strong, nonatomic) NSMutableArray *imageSource;

@property (strong, nonatomic) UIView *buttonView;

@property (strong, nonatomic) UIButton *selectedBtn;

@end

@implementation DragCardViewController

-(void)toLoginButton
{
    DLog(@"一起约");
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = RGB(243,243,243);
    _imageSource = [NSMutableArray new];
    
    //导航栏
    [self createNavigationViewUI];
    
    //选择器
    [self createSegmentViewUI];
    
    //您已选中0位服务者(最多10位)
    [self createShowViewUI];
    
    //卡牌照片
    [self createContainerUI];
    
    //展示ScrollView并可以点击删除
    [self createShowScrollViewUI];
    
    // 获取数据
    [self loadData];
    
    // 给_container赋值
    [_container reloadCardContainer];
    
    //一起约按钮
    _loginButton.frame = CGRectMake(0, kScreenHeight-40, kScreenWidth, loginButtonHeight);
    [_loginButton addTarget:self action:@selector(toLoginButton) forControlEvents:UIControlEventTouchUpInside];
}

//导航栏
-(void)createNavigationViewUI
{
    _navigationView.frame = CGRectMake(0, 0, kScreenWidth, kNavHeight);
    _leftButton.frame = CGRectMake(10, kNavY+(44-30)/2, 30, 30);
    _contentLabel.frame = CGRectMake(40, kNavY+(44-30)/2, kScreenWidth-80, 30);
    _leftButton.titleLabel.font = FONTTWO;
    [_leftButton addTarget:self action:@selector(toCancel) forControlEvents:UIControlEventTouchUpInside];
    _contentLabel.font = FONT18;
}

//选择器
-(void)createSegmentViewUI
{
    NSArray *SegmentArray = @[@"男士SPA",@"足疗",@"看电影",@"陪聊天",@"模特"];
    _SegmentView.frame = CGRectMake(0, _navigationView.frame.size.height, kScreenWidth, 50);
    for(int i=0;i<5;i++)
    {
        UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake((kScreenWidth-20)/5*i+10, (_SegmentView.frame.size.height-30)/2, (kScreenWidth-20)/5-5, 30)];
        [button setTitle:StringFormat(@"%@",SegmentArray[i]) forState:UIControlStateNormal];
        button.backgroundColor = RGB(255, 255, 255);
        button.titleLabel.font = FONT14;
        if(i == 0){
            [button setTitleColor:KRedColor forState:UIControlStateNormal];
            button.layer.borderWidth = 1;
            button.layer.borderColor = KRedColor.CGColor;
            _selectedBtn = button;
        }
        else{
            [button setTitleColor:KBlackColor forState:UIControlStateNormal];
            button.layer.borderWidth = 0;
        }
        button.tag = i;
        [button addTarget:self action:@selector(toSelectInterface:) forControlEvents:UIControlEventTouchUpInside];
        [_SegmentView addSubview:button];
    }
    
}

-(void)toSelectInterface:(UIButton*)sender
{
    if (_selectedBtn) {
        [_selectedBtn setTitleColor:KBlackColor forState:UIControlStateNormal];
        _selectedBtn.layer.borderWidth = 0;
    }
    _selectedBtn = sender;
    [_selectedBtn setTitleColor:KRedColor forState:UIControlStateNormal];
    _selectedBtn.layer.borderWidth = 1;
    _selectedBtn.layer.borderColor = KRedColor.CGColor;
}

//您已选中0位服务者(最多10位)
-(void)createShowViewUI
{
    _showView = [[UIView alloc]initWithFrame:CGRectMake(0, kRealValue(500)+_SegmentView.frame.origin.y+_SegmentView.frame.size.height, kScreenWidth, 21)];
    [self.view addSubview:_showView];
    
    UIImageView *showLeftImageView = [[UIImageView alloc]initWithFrame:CGRectMake(10, (_showView.frame.size.height-1)/2, (kScreenWidth-220)/2-10, 1)];
    showLeftImageView.image = [UIImage imageNamed:@"dragCard_grayImage_icon"];
    [_showView addSubview:showLeftImageView];
    
    _showLabel = [[UILabel alloc]initWithFrame:CGRectMake((kScreenWidth-200)/2, 0, 200, _showView.frame.size.height)];
    NSString *showLabelStr = @"您已选中0位服务者(最多10位)";
    _showLabel.text = showLabelStr;
    _showLabel.textAlignment = NSTextAlignmentCenter;
    _showLabel.adjustsFontSizeToFitWidth = YES;
    [_showView addSubview:_showLabel];
    
    UIImageView *showRightImageView = [[UIImageView alloc]initWithFrame:CGRectMake(_showLabel.frame.origin.x+_showLabel.frame.size.width+10, (_showView.frame.size.height-1)/2, (kScreenWidth-220)/2-10, 1)];
    showRightImageView.image = [UIImage imageNamed:@"dragCard_grayImage_icon"];
    [_showView addSubview:showRightImageView];
}

//选中下面的图片_showScrollView
-(void)createShowScrollViewUI
{
    _showScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(10, _showView.frame.origin.y+_showView.frame.size.height, kScreenWidth-20, 45)];
    _showScrollView.delegate = self;
    _showScrollView.showsVerticalScrollIndicator = NO;
    _showScrollView.showsHorizontalScrollIndicator = NO;
    _showScrollView.bounces = NO;
    [self.view addSubview:_showScrollView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(toDragCardShowScrollView) name:@"DragCard" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(toFrontShowScrollView) name:@"bringSubviewToFront" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(toBackShowScrollView) name:@"sendSubviewToBack" object:nil];
}

-(void)toFrontShowScrollView
{
    [self.view sendSubviewToBack:_showScrollView];//在底层
}

-(void)toBackShowScrollView
{
    [self.view bringSubviewToFront:_showScrollView];//在顶层
}

//逻辑处理选中的图片
-(void)toDragCardShowScrollView
{
    if([Singleton ShareDatabase].currentIndex>_datas.count-1){
        [Singleton ShareDatabase].currentIndex = _datas.count-1;
    }
    NSDictionary *dict = _datas[[Singleton ShareDatabase].currentIndex];
    NSString *imageName = dict[@"image"];
    if(_check == YES){
        BOOL same = NO;
        for(int i=0;i<_imageSource.count;i++){
            NSString *name = StringFormat(@"%@",_imageSource[i]);
            if([name isEqualToString:imageName]){
                same = YES;
            }
        }
        if(same == NO){
            if(_imageSource.count < 10)
            {
                [_imageSource addObject:imageName];
            }
        }
    }
    [self reloadShowScrollView];
}

//逻辑处理选中的图片
-(void)reloadShowScrollView
{
#pragma _showScrollView滑动指定的距离
    if((_showScrollView.frame.size.height+10)*_imageSource.count>_showScrollView.frame.size.width)
    {
        [_showScrollView setContentOffset:CGPointMake(((_showScrollView.frame.size.height+10)*_imageSource.count-_showScrollView.frame.size.width),0) animated:YES];
    }
    
    for(UIView *sub in _showScrollView.subviews){
        [sub removeFromSuperview];
    }
    for(int i=0;i<_imageSource.count;i++){
        UIView *showView = [[UIView alloc]initWithFrame:CGRectMake(i*(_showScrollView.frame.size.height+10), 0, _showScrollView.frame.size.height+10, _showScrollView.frame.size.height)];
        
        UIImageView *showImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, showView.frame.size.width-10, showView.frame.size.height)];
        showImageView.image = [UIImage imageNamed:_imageSource[i]];
        showImageView.layer.masksToBounds = YES;
        showImageView.layer.cornerRadius = showImageView.frame.size.height/2;
        [showView addSubview:showImageView];
        
        UIImageView *smallShowImageView = [[UIImageView alloc]initWithFrame:CGRectMake(showView.frame.size.width-20, 0, 16, 16)];
        smallShowImageView.image = [UIImage imageNamed:@"dragCard_deleteImage_icon"];
        [showView addSubview:smallShowImageView];
        
        UIButton *deleteButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, showView.frame.size.width, showView.frame.size.height)];
        [deleteButton setTitle:_imageSource[i] forState:UIControlStateNormal];
        [deleteButton setTitleColor:KClearColor forState:UIControlStateNormal];
        deleteButton.tag = i;
        [deleteButton addTarget:self action:@selector(todeleteButton:) forControlEvents:UIControlEventTouchUpInside];
        [showView addSubview:deleteButton];
        
        [_showScrollView addSubview:showView];
    }
    _showScrollView.contentSize = CGSizeMake((_showScrollView.frame.size.height+10)*_imageSource.count, _showScrollView.frame.size.height);
    
    _showLabel.text = StringFormat(@"您已选中%lu位服务者(最多10位)",(unsigned long)_imageSource.count);
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    DLog(@"%f",scrollView.contentOffset.x );
    
}

//删除选中的图片
-(void)todeleteButton:(UIButton*)sender
{
    DLog(@"%@",sender.titleLabel.text);
    [_imageSource removeObject:sender.titleLabel.text];
    [self reloadShowScrollView];
}

//创建卡牌照片
-(void)createContainerUI
{
    // 创建 _container
    _container = [[YSLDraggableCardContainer alloc]init];
    _container.frame = CGRectMake(5, _SegmentView.frame.origin.y+_SegmentView.frame.size.height, kScreenWidth-10, kScreenHeight-kNavHeight-loginButtonHeight);
    _container.dataSource = self;
    _container.delegate = self;
    _container.clipsToBounds = YES;
    _container.layer.cornerRadius = 20;
    _container.canDraggableDirection = YSLDraggableDirectionLeft | YSLDraggableDirectionRight;
    [self.view addSubview:_container];
    
    // 创建上下左右四个按钮
    for (int i = 0; i < 2; i++) {
        
        _buttonView = [[UIView alloc]init];
        _buttonView.backgroundColor = [UIColor redColor];
        CGFloat size = 45;
        _buttonView.frame = CGRectMake((_container.frame.size.width-size*3)/2 + (2*size)*i+_container.frame.origin.x,kRealValue(300)+_SegmentView.frame.origin.y+_SegmentView.frame.size.height, size, size);
        [self.view addSubview:_buttonView];
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, size, size);
        [button setBackgroundColor:[UIColor blackColor]];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont fontWithName:@"Futura-Medium" size:18];
        button.clipsToBounds = YES;
        button.layer.cornerRadius = button.frame.size.width / 2;
        button.tag = i;
        [button addTarget:self action:@selector(buttonTap:) forControlEvents:UIControlEventTouchUpInside];
        [_buttonView addSubview:button];
        if (i == 0) { [button setTitle:@"Left" forState:UIControlStateNormal]; }
        if (i == 1) { [button setTitle:@"Right" forState:UIControlStateNormal]; }
    }
}

//卡牌照片的数据源
- (void)loadData
{
    _datas = [NSMutableArray array];
    
    for (int i = 0; i < 13; i++) {
        NSDictionary *dict = @{@"image" : [NSString stringWithFormat:@"photo_sample_0%d",i + 1],
                               @"name" : @"鹰43岁",
                               @"distance":@"83km",
                               @"service":@"线下服务"
                               };
        [_datas addObject:dict];
    }
}

#pragma mark -- Selector喜欢还是不喜欢
- (void)buttonTap:(UIButton *)button
{
    if (button.tag == 0) {
        _check = NO;
        [_container movePositionWithDirection:YSLDraggableDirectionLeft isAutomatic:YES];
    }
    if (button.tag == 1) {
        _check = YES;
        [_container movePositionWithDirection:YSLDraggableDirectionRight isAutomatic:YES];
    }
}

#pragma mark -- YSLDraggableCardContainer DataSource卡牌数据源的具体展示
// 根据index获取当前的view
- (UIView *)cardContainerViewNextViewWithIndex:(NSInteger)index
{
    NSDictionary *dict = _datas[index];
    CardView *view = [[CardView alloc]initWithFrame:CGRectMake(0, 0, _container.frame.size.width, kRealValue(450))];
    view.backgroundColor = [UIColor whiteColor];
    
    view.imageView.image = [UIImage imageNamed:dict[@"image"]];
    NSString *nameString = dict[@"name"];
    view.label.attributedText = [self setMutableAttributedString:nameString didMakeRange:NSMakeRange(1, nameString.length-1) didMakeColor:[UIColor lightGrayColor]];
    
    NSString *distanceString = dict[@"distance"];
    
    view.rightLabel.attributedText = [self setMutableAttributedString:distanceString didMakeImage:[UIImage imageNamed:@"dragCard_positioning_icon"] atIndex:0 didMakeBounds:CGRectMake(0, 0, 15, 15)];
    
    view.botomLabel.text = [NSString stringWithFormat:@"%@",dict[@"service"]];
    return view;
}

// 获取view的个数
- (NSInteger)cardContainerViewNumberOfViewInIndex:(NSInteger)index
{
    return _datas.count;
}

#pragma mark -- YSLDraggableCardContainer Delegate
// 滑动view结束后调用这个方法
- (void)cardContainerView:(YSLDraggableCardContainer *)cardContainerView didEndDraggingAtIndex:(NSInteger)index draggableView:(UIView *)draggableView draggableDirection:(YSLDraggableDirection)draggableDirection
{
    if (draggableDirection == YSLDraggableDirectionLeft) {
        _check = NO;
        [cardContainerView movePositionWithDirection:draggableDirection
                                         isAutomatic:NO];
    }
    
    if (draggableDirection == YSLDraggableDirectionRight) {
        _check = YES;
        [cardContainerView movePositionWithDirection:draggableDirection
                                         isAutomatic:NO];
        
    }
    if (draggableDirection == YSLDraggableDirectionDown) {
        _check = NO;
        [cardContainerView movePositionWithDirection:YSLDraggableDirectionDefault
                                         isAutomatic:NO];
    }
}

// 更新view的状态, 滑动中会调用这个方法
- (void)cardContainderView:(YSLDraggableCardContainer *)cardContainderView updatePositionWithDraggableView:(UIView *)draggableView draggableDirection:(YSLDraggableDirection)draggableDirection widthRatio:(CGFloat)widthRatio heightRatio:(CGFloat)heightRatio
{
    CardView *view = (CardView *)draggableView;
    if (draggableDirection == YSLDraggableDirectionLeft) {
        view.selectedView.backgroundColor = [UIColor clearColor];
        view.selectedView.alpha = widthRatio > 0.8 ? 0.8 : widthRatio;
    }
    
    if (draggableDirection == YSLDraggableDirectionRight) {
        view.selectedView.backgroundColor = [UIColor clearColor];
        view.selectedView.alpha = widthRatio > 0.8 ? 0.8 : widthRatio;
    }
    
}


// 所有卡片拖动完成后调用这个方法
- (void)cardContainerViewDidCompleteAll:(YSLDraggableCardContainer *)container;
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        [container reloadCardContainer];
    });
}


// 点击view调用这个
- (void)cardContainerView:(YSLDraggableCardContainer *)cardContainerView didSelectAtIndex:(NSInteger)index draggableView:(UIView *)draggableView
{
    NSDictionary *dict = _datas[index];
    NSString *nameString = dict[@"name"];
    NSLog(@"%@",nameString);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
